package com.ruoyi.web.controller.system;

import java.util.List;
import java.util.UUID;

import com.ruoyi.system.domain.SysCommissionrecord;
import com.ruoyi.system.mapper.SysDictDataMapper;
import com.ruoyi.system.service.ISysCommissionrecordService;
import com.ruoyi.system.service.ISysDictDataService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.SysDistribution;
import com.ruoyi.system.service.ISysDistributionService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 分销管理Controller
 *
 * @author ruoyi
 * @date 2021-06-06
 */
@RestController
@RequestMapping("/system/distribution")
public class SysDistributionController extends BaseController
{
    @Autowired
    private ISysDistributionService sysDistributionService;

    @Autowired
    private ISysDictDataService iSysDictDataService;

    @Autowired
    private ISysCommissionrecordService iSysCommissionrecordService;

    /**
     * 查询分销管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysDistribution sysDistribution)
    {
        startPage();
        List<SysDistribution> list = sysDistributionService.selectSysDistributionList(sysDistribution);
        return getDataTable(list);
    }

    /**
     * 导出分销管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:export')")
    @Log(title = "分销管理", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(SysDistribution sysDistribution)
    {
        List<SysDistribution> list = sysDistributionService.selectSysDistributionList(sysDistribution);
        ExcelUtil<SysDistribution> util = new ExcelUtil<SysDistribution>(SysDistribution.class);
        return util.exportExcel(list, "分销管理数据");
    }

    /**
     * 获取分销管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:query')")
    @GetMapping(value = "/{distid}")
    public AjaxResult getInfo(@PathVariable("distid") Long distid)
    {
        return AjaxResult.success(sysDistributionService.selectSysDistributionById(distid));
    }

    /**
     * 新增分销管理
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:add')")
    @Log(title = "分销管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysDistribution sysDistribution)
    {
        Long addintegral =Long.parseLong(iSysDictDataService.selectDictValue("sys_ integral","积分值"));
        sysDistribution.setUsernameintegral(addintegral);
        int rows = sysDistributionService.insertSysDistribution(sysDistribution);
        //新人数据
        SysCommissionrecord sysCommissionrecordnew = new SysCommissionrecord();
        sysCommissionrecordnew.setNickname(sysDistribution.getNickname());
        sysCommissionrecordnew.setUsername(sysDistribution.getUsername());
        sysCommissionrecordnew.setUsernameintegral(sysDistribution.getUsernameintegral());
        iSysCommissionrecordService.insertSysCommissionrecord(sysCommissionrecordnew);
        if (rows > 0) {
            String superusername = sysDistribution.getSuperusername();
            SysDistribution distributionfind = new SysDistribution();
            distributionfind.setUsername(superusername);
            List<SysDistribution> sysDistributions = sysDistributionService.selectSysDistributionList(distributionfind);
            if(sysDistributions.size() == 1){
                SysDistribution distribution = sysDistributions.get(0);
                Long usernameintegral = distribution.getUsernameintegral();
                distribution.setUsernameintegral(usernameintegral+addintegral);
                sysDistributionService.updateSysDistribution(distribution);
                //更新或者新增积分佣金记录sys_commissionRecord
                SysCommissionrecord sysCommissionrecord = new SysCommissionrecord();
                sysCommissionrecord.setNickname(distribution.getNickname());
                sysCommissionrecord.setUsername(distribution.getUsername());
                List<SysCommissionrecord> sysCommissionrecords = iSysCommissionrecordService.selectSysCommissionrecordList(sysCommissionrecord);
                if(sysCommissionrecords.size() == 0){
                    sysCommissionrecord.setUsernameintegral(usernameintegral+addintegral);
                    iSysCommissionrecordService.insertSysCommissionrecord(sysCommissionrecord);
                }else{
                    SysCommissionrecord commissionrecord = sysCommissionrecords.get(0);
                    commissionrecord.setUsernameintegral(usernameintegral+addintegral);
                    iSysCommissionrecordService.updateSysCommissionrecord(commissionrecord);
                }
            }
        }
        return toAjax(rows);
    }

    /**
     * 修改分销管理
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:edit')")
    @Log(title = "分销管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysDistribution sysDistribution)
    {
        return toAjax(sysDistributionService.updateSysDistribution(sysDistribution));
    }

    /**
     * 删除分销管理
     */
    @PreAuthorize("@ss.hasPermi('system:distribution:remove')")
    @Log(title = "分销管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{distids}")
    public AjaxResult remove(@PathVariable Long[] distids)
    {
        return toAjax(sysDistributionService.deleteSysDistributionByIds(distids));
    }
    @PostMapping("/checkUser")
    public AjaxResult  checkUser(SysDistribution sysDistribution){
        AjaxResult ajaxResult = AjaxResult.success("");
        List<SysDistribution> sysDistributions = sysDistributionService.selectSuperSysDistributionList(sysDistribution);
        if(sysDistributions.size() == 0){
            ajaxResult = AjaxResult.error("上级信息有误,请重新填写!");
            ajaxResult.put("codeResult","500");
        }
        return ajaxResult;
    }

    /**
     * @description 生成验证码
     * @author SDL
     * @date 2021/6/6 16:33
     * * @param null
     * @return
     */
    @GetMapping("/getCode")
    public AjaxResult getCode(){
        AjaxResult ajax = AjaxResult.success();
        String[] chars = new String[] { "a", "b", "c", "d", "e", "f",
                "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s",
                "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I",
                "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        try {
            StringBuffer shortBuffer = new StringBuffer();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            for (int i = 0; i < 8; i++) {
                String str = uuid.substring(i * 4, i * 4 + 4);
                int x = Integer.parseInt(str, 16);
                shortBuffer.append(chars[x % 0x3E]);
            }
            ajax.put("integral", shortBuffer.toString());
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return ajax;
    }
}
